package com.tkjt.pms.modules.scoring.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tkjt.pms.common.entity.*;
import com.tkjt.pms.common.utils.*;
import com.tkjt.pms.common.vos.RequestJson;
import com.tkjt.pms.modules.common.mapper.*;
import com.tkjt.pms.modules.kpiadmin.mapper.DataGridMapper;
import com.tkjt.pms.modules.scoring.mapper.TkScoringMapper;
import com.tkjt.pms.modules.scoring.mapper.TkScoringMirrorMapper;
import com.tkjt.pms.modules.scoring.model.GradeDetailDatagridResponseModel;
import com.tkjt.pms.modules.scoring.model.GradeViewDatagridResponseModel;
import com.tkjt.pms.modules.scoring.model.ScoreCommentQueryRequestModel;
import com.tkjt.pms.modules.scoring.model.ScoreCommentQueryResponseModel;
import com.tkjt.pms.modules.scoring.vo.RecordsBean;
import com.tkjt.pms.server.common.DepartAndInfoTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Service("tkScoringBizServiceMirror")
@Transactional
public class TkScoringBizServiceMirror extends TkScoringBizServiceBase  {
    @Autowired
    private TkIndexValueMapper tkIndexValueMapper;
    @Autowired
    private TkIndexInfoMapper tkIndexInfoMapper;
    @Autowired
    private TkIndexValueAuditMapper tkIndexValueAuditMapper;
    @Autowired
    private TkIndexValueCommentsMapper tkIndexValueCommentsMapper;
    @Autowired
    private TkScoringMirrorMapper tkScoringMirrorMapper;
    @Autowired
    private PMSCommonMapper commonMapper;
    @Autowired
    private TkIndexReportCtrlMirrorMapper tkIndexReportCtrlMirrorMapper;
    @Autowired
    private TkIndexValueMirrorMapper tkIndexValueMirrorMapper;
    @Autowired
    private SysDepartMapper sysDepartMapper;
    @Autowired
    private SysUserMirrorMapper sysUserMirrorMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private DepartAndInfoTool departAndInfoTool;
    @Autowired
    private DataGridMapper dataGridMapper;
    @Autowired
    private SysDepartMirrorMapper sysDepartMirrorMapper;
    @Override
    public GradeViewDatagridResponseModel gradeViewDatagrid(String year, String dataType) {
        GradeViewDatagridResponseModel model=new GradeViewDatagridResponseModel();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userName = loginUser.getUsername();
        String currentOrgCode = loginUser.getOrgCode();
        QueryWrapper<SysDepart> departQuery = new QueryWrapper<>();
        departQuery.lambda().eq(SysDepart::getOrgCode,currentOrgCode);
        SysDepart sysDepart = sysDepartMapper.selectOne(departQuery);
        //根据当前用户部门名获取去年对应年份镜像部门
        QueryWrapper<SysDepartMirror> departMirrorQuery = new QueryWrapper<>();
        departMirrorQuery.lambda().eq(SysDepartMirror::getDepartName,sysDepart.getDepartName());
        departMirrorQuery.lambda().eq(SysDepartMirror::getMirrorCode,"MC"+year);
        SysDepartMirror sysDepartMirror = sysDepartMirrorMapper.selectOne(departMirrorQuery);
        if(sysDepartMirror == null){
            model.setRecords(null);
            model.setTotal(0);
            return model;
        }
        String myOrgCode = sysDepartMirror.getOrgCode();
        List<String> orgCodes = tkIndexReportCtrlMirrorMapper.getOrgCodeAllow(myOrgCode,"MC"+year);

        if (!orgCodes.contains(myOrgCode)) {
            orgCodes.add(myOrgCode);
        }
        QueryWrapper<TkIndexValueMirror> qw = new QueryWrapper<>();
        qw.in("INDEX_DEPART", orgCodes.toArray());
        List<String> infoAttrs = new ArrayList<>();
        infoAttrs.add(InfoAttrUtil.ZONG_JI);
        List<String> indexValueCodes = departAndInfoTool.getIndexValueCodesByParam(null,infoAttrs);
        qw.in("INDEX_VALUE_CODE",indexValueCodes );
        qw.eq("DATA_TYPE",dataType);
        qw.eq("MIRROR_CODE","MC"+year+"12");
        List<TkIndexValueMirror> list = tkIndexValueMirrorMapper.selectList(qw);

        List<GradeViewDatagridResponseModel.RecordsBean> records = new ArrayList<>();

        String yearMonth = EsDateUtils.getIndexYearMonth(new Date());
        for (TkIndexValueMirror item : list) {
            GradeViewDatagridResponseModel.RecordsBean recordsBean=new GradeViewDatagridResponseModel.RecordsBean();
            recordsBean.setIndexOrgCode(item.getIndexDepart());
            QueryWrapper<SysDepartMirror> sysDepartQueryWrapper = new QueryWrapper<>();
            sysDepartQueryWrapper.eq("org_code", item.getIndexDepart());
            sysDepartQueryWrapper.eq("mirror_code","MC"+year);
            recordsBean.setIndexOrgName(sysDepartMirrorMapper.selectOne(sysDepartQueryWrapper).getDepartName());
            recordsBean.setScorerCode(item.getIndexScorer());
            String indexScorer = item.getIndexScorer();
            if(indexScorer != null){
                QueryWrapper<SysUserMirror> sysUserMirrorWrapper = new QueryWrapper<>();
                sysUserMirrorWrapper.lambda().eq(SysUserMirror::getUsername,indexScorer);
                SysUserMirror user = sysUserMirrorMapper.selectOne(sysUserMirrorWrapper);
                if(user != null){
                    recordsBean.setScorerName(user.getRealname());
                }
            }
            String indexValueCode = item.getIndexValueCode();
            String indexDepart = item.getIndexDepart();

            Map<String, String> mTotalMirrorMap = new HashMap<>();
            String[] roleCodes = {"ykkpiowner","ykgm"};
            List<String> userNames = sysUserMirrorMapper.selectUserNameByRoleCodes(roleCodes);
            userNames.add("system");
            List<String> currentUserNames = sysUserMapper.selectUserNameByRoleCodes(roleCodes);
            currentUserNames.add("system");
            for (int index = 1; index <= 12; index++) {
                // String mirrorCode = "MC"+""+"11";
                String mirrorCode = TkIndexUtils.getMirrorCode(year, index);
                QueryWrapper<TkIndexValueMirror> qwMirror = new QueryWrapper<>();
                qwMirror.eq("MIRROR_CODE",mirrorCode);
                qwMirror.eq("INDEX_DEPART",indexDepart);
                qwMirror.eq("INDEX_SCORER",indexScorer);
                qwMirror.eq("INDEX_VALUE_CODE",indexValueCode);
                qwMirror.in("INDEX_EXECUTOR",userNames);
                qwMirror.eq("DATA_TYPE",dataType);
                TkIndexValueMirror mirrorEntity = tkIndexValueMirrorMapper.selectOne(qwMirror);
                if (mirrorEntity != null) {
                    mTotalMirrorMap.put("m" + mirrorCode.substring(6), DepartCode.formateForDouble(mirrorEntity.getMTotal()).toString());
                } else {
                    mTotalMirrorMap.put("m" + mirrorCode.substring(6), "0.0");
                }
            }
            recordsBean.setM01(mTotalMirrorMap.get("m01"));
            recordsBean.setM02(mTotalMirrorMap.get("m02"));
            recordsBean.setM03(mTotalMirrorMap.get("m03"));
            recordsBean.setM04(mTotalMirrorMap.get("m04"));
            recordsBean.setM05(mTotalMirrorMap.get("m05"));
            recordsBean.setM06(mTotalMirrorMap.get("m06"));
            recordsBean.setM07(mTotalMirrorMap.get("m07"));
            recordsBean.setM08(mTotalMirrorMap.get("m08"));
            recordsBean.setM09(mTotalMirrorMap.get("m09"));
            recordsBean.setM10(mTotalMirrorMap.get("m10"));
            recordsBean.setM11(mTotalMirrorMap.get("m11"));
            recordsBean.setM12(mTotalMirrorMap.get("m12"));

            //todo 镜像部门可能会发生变化，没有办法在镜像列表数据上展示当前考核数据
            //增加最近两个月份得分对比信息，方便前端页面处理
//            {
//                String currentYear = yearMonth.substring(0,4);
//                String currentMonth = yearMonth.substring(4);
//                Map<String,Object> param = new HashMap<>();
//                param.put("month","m"+currentMonth);
//                param.put("indexDepart",currentOrgCode);
//                param.put("indexScorer",userName);
//                param.put("indexValueCode",indexValueCode);
//                param.put("year",currentYear);
//                param.put("indexExecutors",currentUserNames);
//                param.put("dataType",dataType);
//                Map<String,Object> currentMap = dataGridMapper.getMonthIndexValueForParam(param);
//                GradeViewDatagridResponseModel.RecordsBean.RecentMonthValue recentMonth = new GradeViewDatagridResponseModel.RecordsBean.RecentMonthValue();
//                recentMonth.setName(currentYear+"年"+currentMonth+"月");
//                if(currentMap != null){
//                    recentMonth.setValue(formateForDouble(currentMap.get("m"+currentMonth).toString()));
//                }
//                recordsBean.addRecentMonth(recentMonth);
//                String lastMonth = "";
//                if(!"01".equals(currentMonth)){
//                    if(currentMonth.startsWith("0")){
//                        lastMonth = "0"+(Integer.valueOf(currentMonth.substring(1)) - 1);
//                    }else{
//                        lastMonth = String.valueOf(Integer.valueOf(currentMonth) -1);
//                    }
//
//                    param.put("month","m"+lastMonth);
//                    currentMap = dataGridMapper.getMonthIndexValueForParam(param);
//                    recentMonth = new GradeViewDatagridResponseModel.RecordsBean.RecentMonthValue();
//                    recentMonth.setName(currentYear+"年"+lastMonth+"月");
//                    if(currentMap != null){
//                        recentMonth.setValue(formateForDouble(currentMap.get("m"+lastMonth).toString()));
//                    }
//                    recordsBean.addRecentMonth(recentMonth);
//                }else{
//                    lastMonth = "12";
//                    String lastYear = String.valueOf(Integer.valueOf(currentYear)-1);
//                    param.put("mirrorCode","MC"+lastYear+lastMonth);
//                    param.put("month","m"+lastMonth);
//                    currentMap = dataGridMapper.getMirrorMonthIndexValueForParam(param);
//                    recentMonth = new GradeViewDatagridResponseModel.RecordsBean.RecentMonthValue();
//                    recentMonth.setName(lastYear+"年"+lastMonth+"月");
//                    if(currentMap != null){
//                        recentMonth.setValue(formateForDouble(currentMap.get("m"+lastMonth).toString()));
//                    }
//                    recordsBean.addRecentMonth(recentMonth);
//                }
//            }
            records.add(recordsBean);
        }
        model.setRecords(records);
        model.setTotal(records.size());
        return model;
    }

    @Override
    public GradeDetailDatagridResponseModel gradeDetailDatagrid(Map<String,Object> request, String dataType) {
        GradeDetailDatagridResponseModel model=new GradeDetailDatagridResponseModel();
        String yearMonth = request.get("yearMonth").toString();
        String year=yearMonth.substring(0,4);
        String indexDepart = request.get("indexDepart").toString();//被评分部门
        String indexScorer = request.get("indexScorer").toString();//被评分人
        int pageNo = Integer.valueOf(request.get("pageNo").toString());
        int pageSize = Integer.valueOf(request.get("pageSize").toString());
        Map<String,Object> param = new HashMap<>();
        param.put("year",year);
        param.put("weightM","weight_m"+yearMonth.substring(4));
        param.put("mirroCode","MC"+yearMonth);
        param.put("indexDepart",indexDepart);
        param.put("indexScorer",indexScorer);
        String[] roleCodes = {"ykkpiowner","ykgm"};
        List<String> userNames = sysUserMirrorMapper.selectUserNameByRoleCodes(roleCodes);
        userNames.add("system");
        param.put("indexExecutors",userNames);
        param.put("dataType",dataType);
        param.put("min",(pageNo-1)*pageSize);
        param.put("max",pageSize);
        List<RecordsBean> list = tkScoringMirrorMapper.selectIndexValueMirrorPage(param);
        int count = tkScoringMirrorMapper.selectIndexValueMirrorCount(param);
        for(int i = 0 ; i < list.size() ; i ++ ){
            list.get(i).setM01(formateForDouble(list.get(i).getM01()));
            list.get(i).setM02(formateForDouble(list.get(i).getM02()));
            list.get(i).setM03(formateForDouble(list.get(i).getM03()));
            list.get(i).setM04(formateForDouble(list.get(i).getM04()));
            list.get(i).setM05(formateForDouble(list.get(i).getM05()));
            list.get(i).setM06(formateForDouble(list.get(i).getM06()));
            list.get(i).setM07(formateForDouble(list.get(i).getM07()));
            list.get(i).setM08(formateForDouble(list.get(i).getM08()));
            list.get(i).setM09(formateForDouble(list.get(i).getM09()));
            list.get(i).setM10(formateForDouble(list.get(i).getM10()));
            list.get(i).setM11(formateForDouble(list.get(i).getM11()));
            list.get(i).setM12(formateForDouble(list.get(i).getM12()));
            list.get(i).setmTotal(formateForDouble(list.get(i).getmTotal()));
            //当指标为达成率时，该字段为true， 表示：该字段可以查看图形报表
            //TEMP
            List<String> infoAttrs = new ArrayList<>();
            infoAttrs.add(InfoAttrUtil.DA_CHENG_LV);

            if(infoAttrs.contains(list.get(i).getIndexValueAttr())) {
                list.get(i).setShowChart(true);
            } else {
                list.get(i).setShowChart(false);
            }

            //retVo.setShowLine(indexValueName.contains("得分"));
            infoAttrs = new ArrayList<>();
            infoAttrs.add(InfoAttrUtil.XIAO_JI);
            infoAttrs.add(InfoAttrUtil.ZONG_JI);
            //当指标为得分时（小计、总计），该字段为true， 表示：该字段所在的行背景颜色要突出
            if(infoAttrs.contains(list.get(i).getIndexValueAttr())) {
                list.get(i).setShowLine(true);
            } else {
                list.get(i).setShowLine(false);
            }
        }
        model.setTotal(count);
        model.setCurrent(pageNo);
        int pages = count / pageSize;
        if (count % pageSize > 0) {
            pages += 1;
        }
        model.setPages(pages);
        model.setSearchCount(true);
        model.setRecords(list);
        model.setSize(pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("orgCode",indexDepart);
        map.put("mirrorCode","MC"+year);
        String departName = sysDepartMirrorMapper.queryOrgNameByOrgCode(map);
        model.setGradeDetailTips(departName+"-"+year+"年"+yearMonth.substring(4)+"月");
        return model;
    }

}
